package xin.yangda.poiplus.test.controller;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import xin.yangda.poiplus.constants.PoiPlusFileExtend;
import xin.yangda.poiplus.designer.SimpleXlsDesigner;
import xin.yangda.poiplus.designer.csv.CsvDesigner;
import xin.yangda.poiplus.handler.ExcelReadHandler;
import xin.yangda.poiplus.loader.SimpleXlsxLoader;
import xin.yangda.poiplus.pojo.ExcelData;
import xin.yangda.poiplus.pojo.ExcelErrorField;
import xin.yangda.poiplus.test.entity.UserEntity;
import xin.yangda.poiplus.test.service.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * @author yangdaxin
 * @version 创建时间 2019/1/21 16:32
 */
@RestController
@RequestMapping(value = "/user", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class UserController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    private static final String XLS_EXCEL_TEMP_PATH = "templates/user.xls";
    private static final String XLSX_EXCEL_TEMP_PATH = "templates/user.xlsx";

    @Autowired
    private UserService userService;

    /**
     * 下载excel（有模板）
     *
     * @param request
     * @param response
     */
    @GetMapping(value = "/excelTemp")
    public void exportExcelTemp(HttpServletRequest request, HttpServletResponse response) {
        // 打开模板
//        InputStream inputStream = getClass().getClassLoader().getResourceAsStream(XLS_EXCEL_TEMP_PATH);
        InputStream inputStream = getClass().getClassLoader().getResourceAsStream(XLSX_EXCEL_TEMP_PATH);
        try (SimpleXlsDesigner simpleXlsDesigner = new SimpleXlsDesigner(inputStream)) {
            // 填充数据源
            Map<String, String> map = Maps.newConcurrentMap();
            map.put("createUser", "yangdaxin");
            map.put("createTime", "2019-01-18 18:05:00");

            ExcelData<UserEntity> excelData = new ExcelData<>(UserEntity.class, map, userService.queryList());
            simpleXlsDesigner.setData(excelData);

            // 数据加工
            simpleXlsDesigner.process();

            // 保存Excel
            simpleXlsDesigner.download(request, response, PoiPlusFileExtend.XLS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载excel（无模板）
     *
     * @param request
     * @param response
     */
    @GetMapping(value = "/excel")
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
        try (SimpleXlsDesigner simpleXlsDesigner = new SimpleXlsDesigner()) {
            // 填充数据源
            ExcelData<UserEntity> excelData = new ExcelData<>(UserEntity.class, userService.queryList());
            simpleXlsDesigner.setData(excelData);

            // 数据加工
            simpleXlsDesigner.process();

            // 保存Excel
            simpleXlsDesigner.download(request, response, PoiPlusFileExtend.XLS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载模板
     *
     * @param request
     * @param response
     */
    @GetMapping(value = "/template")
    public void exportTemplate(HttpServletRequest request, HttpServletResponse response) {
        try (SimpleXlsDesigner simpleXlsDesigner = new SimpleXlsDesigner()) {
            // 填充数据源
            ExcelData<UserEntity> excelData = new ExcelData<>(UserEntity.class);
            simpleXlsDesigner.setData(excelData);

            // 数据加工
            simpleXlsDesigner.process(true);

            // 保存Excel
            simpleXlsDesigner.download(request, response, PoiPlusFileExtend.XLS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载CSV
     *
     * @param request
     * @param response
     */
    @GetMapping(value = "/csv")
    public void exportCsv(HttpServletRequest request, HttpServletResponse response) {
        ExcelData<UserEntity> excelData = new ExcelData<>(UserEntity.class, userService.queryList());
        CsvDesigner.build(excelData).download(request, response);
    }

    /**
     * Excel导入
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/import")
    public ResponseEntity<?> importExcel(@RequestParam("excelFile") MultipartFile file) throws IOException {
        // 执行文件导入.
        long beginTimeMillis = System.currentTimeMillis();
        final List<UserEntity> userList = Lists.newArrayList();
        final List<Map<String, Object>> error = Lists.newArrayList();

        SimpleXlsxLoader.build(UserEntity.class).readXlsx(file.getInputStream(), new ExcelReadHandler<UserEntity>() {
            @Override
            public void onSuccess(int sheet, int row, UserEntity userEntity) {
                // 当前行读取成功, 入库或加入批量入库队列.
                userList.add(userEntity);
            }

            @Override
            public void onError(int sheet, int row, List<ExcelErrorField> errorFields) {
                // 当前行读取失败, 获取失败详情.
                error.add(ImmutableMap.of("row", row, "errorFields", errorFields));
            }
        });

        long time = ((System.currentTimeMillis() - beginTimeMillis) / 1000L);

        LOGGER.info("数据量: {}, 耗时: {}秒", userList.size(), time);

        ImmutableMap<String, Object> retJsonMap = ImmutableMap.of(//
                "time", "耗时" + time + "秒",
                "data", userList,
                "error", error
        );

        return ResponseEntity.ok(retJsonMap);
    }
}
